<?php

    include 'dbconfig.php'; 
    mysql_select_db($db, $con);

    $name =  mysql_real_escape_string($_POST['name']);
    $area1 = mysql_real_escape_string($_POST['area1']);
    $credits = intval(mysql_real_escape_string($_POST['credits']));
    $external = mysql_real_escape_string($_POST['external']) == "external" ? 1 : 0;
    
    $continuous = 1; // - $external;
    
    $hash = md5($name.$area1.mt_rand());
    
    $query = "INSERT INTO course_templates VALUES (0, '$hash', '$name', '$area1', '', '', $credits, 1, 1, $external, $continuous, 0)";
    mysql_query($query);   
    
    $query = "SELECT value FROM globals WHERE keyname = 'startyear' LIMIT 1";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    $startyear = intval($row['value']);
    
    $query = "SELECT value FROM globals WHERE keyname = 'endyear' LIMIT 1";
    $result = mysql_query($query);
    $row = mysql_fetch_array($result);
    $endyear = intval($row['value']);


    $query = "INSERT INTO course_instances VALUES ";
    for ($i = $startyear; $i<=$endyear; $i++) {
        $instance_hash = md5($name.$i.mt_rand());        
        $query .= "(0, '$instance_hash', '$hash', $i, 0, '', ''), ";
        $query .= "(0, '$instance_hash', '$hash', $i, 1, '', ''), ";    
    }
    $query .= "(0, '$instance_hash', '$hash', ".($startyear-1).", 1, '', '')";
    mysql_query($query);   
    //echo $query;

    echo $hash;
    

?>